<?php
require_once('../../libraryfiles/config.php');
require_once('../../includefiles/img-resize-class.php');
	
$action = isset($_GET['action']) ? $_GET['action'] : '';

switch($action)
{
	case 'add' :
		add();
		break;
	
	case 'apply' :
		add(true);

	case 'addexist' :
		addexist();
		break;
		
	case 'delselected' :
		deleteSelected();
		break;
		
	case 'deletet_count' :
		deletetCount();
		break;		
		
	case 'publish' :
		publishSelected();
		break;
	
	case 'updatePrice':	
		updatePrice();
		break;
		
	case 'displaypro':
		display();
		break;		
	
	case 'diplayexist':		
		displayexit();
		break;
						
	case 'search_pro':
		search_pro();
		break;
		
	default :
	    // if action is not defined or unknown
		// move to main user page
		header('Location: index.php');
		exit();
}




function add(){
	
	$ID 		= $_POST['hidid'];
	$pro_name 	= ampReplace($_POST['new_proname']);
    $pro_name 	= preg_replace(array('/\x5C(?!\x5C)/u', '/\x5C\x5C/u'), array('','\\'), $pro_name);
	$pro_name = addslashes($pro_name);
    $escape     = $pro_name;
    $pro_name = escape_query($escape);
	$pro_typ 	= $_POST['selectType'];
	
	$made_in	= $_POST['selectCoun'];
	$pro_price	= $_POST['price'];
	$pro_reg_price      = $_POST['price_regular']; 
	$laboratory = '';
    $pro_appe_color     = $_POST['txtcheckboxProduct'];   
    $pro_appe_size      = $_POST['txtsizename'];
    $GetPostBrandName   =$_POST['selectType'];
	$pharmacy_id = $_SESSION['acc_id'];
	$pid                = $_POST['hidpid'];    

	$short_desc = str_replace("'","'",$_POST['shot_disc']);
	$short_desc = str_replace("\"../images/","\"" . W_IMAGES_DIR,$short_desc);
	$short_desc = str_replace("\"../../images/","\"" . W_IMAGES_DIR,$short_desc);	
	$short_desc = addslashes($short_desc);
	
	$desc = str_replace("'","'",$_POST['txtdesc']);
	$desc = str_replace("\"../images/","\"" . W_IMAGES_DIR,$desc);
	$desc = str_replace("\"../../images/","\"" . W_IMAGES_DIR,$desc);	
	$desc = addslashes($desc);

        //color    
        $count_s = count($pro_appe_size);
        $count_c = count($pro_appe_color);
        if($count_s>$count_c)
        {
           $mix = $pro_appe_size;
        }
        else if($count_c>$count_s)
        {
           $mix = $pro_appe_color;
        }
        else if($count_c==$count_s)
        {
           $mix = $pro_appe_color;
        }
        // end color   
          
        	
	$link = $detectExist_q = "";
	$modify = false;
	if(!empty($ID)){
		$modify = true;
		$link = "&id=" . $ID;
		$detectExist_q .= " AND id != " . $ID;
	}
		
	//Statment to detect the entry Lesson Category Name exist
	if(existRecord("tblproduct","product_name = '$pro_name' $detectExist_q")){
		header('Location: index.php?view=add' . $link . $qstr . '&error=' . urlencode('Name already taken. Please choose another one'));
		exit();
	}
	else if($modify){
	   
	   //color, clear before insert
       $mixtb   = mysql_query("DELETE FROM tbl_color_size WHERE pid=$ID");
       
        foreach($mix as $key => $value)
        {
           $color = $pro_appe_color[$key];
           $getBrand=$GetPostBrandName;
           $size=$pro_appe_size[$key];
           $co_insert = mysql_query("INSERT INTO tbl_color_size (color_id,size_id, pid, brand_name) VALUES ('$color','$size','$ID','$getBrand')");
        }
       // end color
       
              
		
		//Statement to update the lesson category info
		$update_q = "UPDATE tblproduct 
					 SET product_name = '$pro_name', short_desciption = '$short_desc', product_description = '$desc', mdate = NOW(), product_type = '$pro_typ', owner = $pharmacy_id 
					 WHERE id = $ID";
		$last_id = $ID;
		mysql_query($update_q);
		
			$sql2 = "DELETE FROM tblproduct_in_category WHERE product_id = $last_id";
			mysql_query($sql2);
			
			//Pharmacy Query
        if($_POST['selectCoun'][0]!=0)
        { 
            foreach($made_in as $key => $value)
            {
    			$country = $value;
    			$price = $pro_price[$key];
                $pro_reg_price   = $pro_reg_price[$key];
    			$labor = $laboratory[$key];
    			$pids = $pid[$key];	
    			$sql_del = "DELETE FROM tblproduct_in_pharmacy WHERE pid=$pids";
    			mysql_query($sql_del);
    			$sql_pha            = "INSERT INTO tblproduct_in_pharmacy(product_id, pharmacy_id, country_id, regular_price, price, status) VALUES($last_id, $pharmacy_id, $country, '$pro_reg_price', '$price', 1)";
    			mysql_query($sql_pha);
            }            
        } 
        else
        {
            $pids = $pid[0];
            $sql_del = "DELETE FROM tblproduct_in_pharmacy WHERE pid=$pids";
            mysql_query($sql_del);
			$price              = $pro_price[0];
            $pro_reg_price      = $pro_reg_price[0];
            $sql_pha            = "INSERT INTO tblproduct_in_pharmacy(product_id, pharmacy_id, regular_price, price, status) VALUES($last_id, $pharmacy_id, '$pro_reg_price', '$price',1)";
			$in_com = mysql_query($sql_pha);
        } 
         
		if(!empty($_POST['imagefile']))
        {
            UnlinkImageDelete();
        }
		
        // delete image selected
         if(!empty($_POST['DelImage'])){
            UnlinkSingleImageDelete();
         }
         // end delete image selected
     
	}
	else{
	//Ordering number
	$ordering_q = "SELECT MAX(product_ordering) AS ordering 
				   FROM tblproduct";
	$ordering_r = mysql_query($ordering_q);
	$ordering_info = mysql_fetch_assoc($ordering_r);
	extract($ordering_info);
	$ordering += 1;
	
	// Product Query
	$insert_q = "INSERT INTO tblproduct(product_name, product_type, product_ordering, cdate, mdate, short_desciption, product_description, status, owner) VALUES('$pro_name', '$pro_typ', '$ordering', NOW(), NOW(),'$short_desc', '$desc', 1, $pharmacy_id)";
	mysql_query($insert_q);
	
	$last_id = mysql_insert_id();
    
	// color insert  
        foreach($mix as $key => $value)
        {
           $color = $pro_appe_color[$key];
           $getBrand=$GetPostBrandName;
           $size=$pro_appe_size[$key];
           $co_insert = mysql_query("INSERT INTO tbl_color_size (color_id,size_id, pid, brand_name) VALUES ('$color','$size','$last_id','$getBrand')");
        }
        // end color insert
	
	   //Pharmacy Query
        if($_POST['selectCoun'][0]!=0)
            { 
    	   foreach($made_in as $key => $value)
                {
        			$country = $value;
        			$price = $pro_price[$key];
        			$labor = $laboratory[$key];
                	$sql_pha = "INSERT INTO tblproduct_in_pharmacy(product_id, pharmacy_id, country_id, price, laboratory, status) VALUES($last_id, $pharmacy_id, $country, '$price', '$labor',1)";
                	mysql_query($sql_pha);
                }
        	}
            else
            {
                $price              = $pro_price[0];
                $pro_reg_price      = $pro_reg_price[0];
                $sql_pha         = "INSERT INTO tblproduct_in_pharmacy(product_id, pharmacy_id, regular_price, price, status) VALUES($last_id, $pharmacy_id, '$pro_reg_price', '$price',1)";
			$in_com = mysql_query($sql_pha);
                
            }        
                    
        }
 
 
 
            //for uplaod image  
                $imagefile = $_FILES['imagefile'];
                //print_r($imagefile['name']);die();
            	$arrayTemp = array();
            	foreach($imagefile as $index => $name){
            	       
            		foreach($name as $key => $value){
            			$arrayTemp[$key][$index] = $value;
                       
            		}
            		
            	}
            	//print_r($arrayTemp);exit;
            	foreach($arrayTemp as $newimage){
                  $ftmp         = $newimage['tmp_name']; 
                  $fname        = $newimage['name'];
                  $fsize        = $newimage['size'];
                  $ftype        = $newimage['type'];
                  $image        = new SimpleImage(); // declare object
                  $check_type   = $image->checkType($ftype); // check file type
                  $check_size   = $image->checkSize($fsize); // check file size            
            
                  if (true == $check_type) {
                     if (true == $check_size) {
                        $image->load($ftmp);        
                        if (file_exists('uploads/' . $fname)) 
                        {
                           $fname = $image->random(5) . '-' . $fname;
                           $image->save('uploads/' . $fname);
            
                           $image->resize(300, 300);
                           $image->save('uploads/300x300-' . $fname);
                           
                           $image->resize(60, 60);
                           $image->save('uploads/60x60-' . $fname);
                        } else {
                           $image->save('uploads/' . $fname);
                           // create thumbnail
                           $image->resize(300, 300);
                           $image->save('uploads/300x300-' . $fname);
                           
                           $image->resize(60, 60);
                           $image->save('uploads/60x60-' . $fname);
                        } 
            		$sql_img = "INSERT INTO tblimage(images,thumbnail,original_img,product_id) VALUES('300x300-".$fname."','60x60-".$fname."','$fname',$last_id)";
            		mysql_query($sql_img);
                     } else {
                        //$_SESSION['error'] = 'File size is bigger than 2 MB!';
                        //header('Location: ../../index.php?id=profile');
                     }
                  } else {
                     //$_SESSION['error'] = 'File not support!';
                     //header('Location: ../../index.php?id=profile');
                  } 
            	}
        //end for upload image
 
 
 
        
	// Category Query
	$selectCate = isset($_POST['selectcat'])?$_POST['selectcat']:'';
	foreach($selectCate as $value){
		$sql_cate = "INSERT INTO tblproduct_in_category VALUES($value,$last_id)";	
		mysql_query($sql_cate);
	}    	
		header('Location: ' . $_SESSION['shop_return_url']);
}

function addexist(){
		$id			= $_POST['hidnewid'];
		$made_in	= $_POST['selectCountry'];
		$pro_price	= $_POST['newprice'];
		$pharmacy_id = $_SESSION['acc_id'];
		$laboratory = $_POST['new_laboratory'];
		$pid = $_POST['hidupdate'];
		$link = $detectExist_q = "";
			$modify = false;
			if(!empty($pid)){
				$modify = true;
				$link = "&id=" . $pid;
				$detectExist_q .= " AND pid != " . $pid;
			}
		// exist record
		foreach($made_in as $key => $value){
		$country = $value;
		$price = $pro_price[$key];
		$labor = addslashes($laboratory[$key]);
		$pids = $pid[$key];
		$sql_e = "SELECT * FROM tblproduct_in_pharmacy WHERE product_id = $id AND country_id = $country AND pharmacy_id = $pharmacy_id AND laboratory = '$labor' AND pid!=$pids";
		$result_e = mysql_query($sql_e);
		}
		if(dbNumRows($result_e)){
			$error = 'You have this product already !';	
			header("Location: index.php?view=add&error=$error");
			exit();
		}else if($modify){
			foreach($made_in as $key => $value){
			$country = $value;
			$price = $pro_price[$key];
			$labor = addslashes($laboratory[$key]);
			$pids = $pid[$key];	
			$sql_del = "DELETE FROM tblproduct_in_pharmacy WHERE pid=$pids";
			mysql_query($sql_del);
			$sql_pha = "INSERT INTO tblproduct_in_pharmacy(product_id, pharmacy_id, country_id, price, laboratory, status) VALUES($id, $pharmacy_id, $country, '$price', '$labor',1)";
			mysql_query($sql_pha);
			}         
		}else{
		//Pharmacy Query
		foreach($made_in as $key => $value){
		$country = $value;
		$price = $pro_price[$key];
		$labor = $laboratory[$key];
		$sql_pha = "INSERT INTO tblproduct_in_pharmacy(product_id, pharmacy_id, country_id, price, laboratory, status) VALUES($id, $pharmacy_id, $country, '$price', '$labor',1)";
		mysql_query($sql_pha);			
			}
		}
		header("Location: index.php");
}

function search_highlight($needle, $replace, $haystack)
{
 $haystack = str_replace($needle,$replace,$haystack);
 return $haystack;
}

function search_pro(){
		$pro_name = addslashes($_GET['searchword']);
		$sql = "SELECT * FROM tblproduct WHERE product_name LIKE '$pro_name%' AND status = 1";
		$result = mysql_query($sql);
		if(dbNumRows($result)){
		echo '<span id="id" style="color:#999;"><em>Search Result...</em></span><br /><br />';
		$i = 1;
			while($row = mysql_fetch_assoc($result)){
				$sql_img = "SELECT thumbnail FROM tblimage WHERE product_id = ".$row['id']." LIMIT 0,1";
				$result_img = mysql_query($sql_img);
				$row_img = mysql_fetch_assoc($result_img);
				
				if($i%2){
				$class = 'search_row1';	
				}else{
				$class = 'search_row2';	
				}
				$i++;
		?>
        <div style="width:320px; height:auto;">
        <div style="float:left; width:70px;">
        <?php
		if($row_img['thumbnail']!=""){
			$thumbnail_i = 	$row_img['thumbnail'];
		}else{
			$thumbnail_i = 	'no-image-small.png';
		}
		?>
        <img src="<?php echo W_S_IMAGES_DIR.$thumbnail_i; ?>" class="border" width="70" />
        </div>
        <div style="float:left; padding-left:15px; padding-top:10px; width:180px;"><strong style="color:#06C;"><?php echo $row['product_name']; ?></strong><br />
        <em style="color:#666;">( Product type : <?php echo $row['product_type'];?> )</em>
        </div>
        <div style="float:right; padding-top:10px;"><a href="#1" id="<?php echo $row['id'];?>" class="addproduct"><img src="<?php echo W_ROOT;?>/images/btnadd.jpg" border="0" /></a></div>
        </div>
        <div style="clear:both; height:5px;"></div>
        <?php
			}// end while
			?>
            <br />
        <img src="<?php echo W_ROOT;?>/images/add_icon.jpg" border="0" /> 
        <a style="color:#00F; text-decoration:underline; cursor:pointer;" id="clicktoadd" onclick="$('#formaddnew').show();"><em>Add New Product</em></a>
            <?php
		}else{
			?>
        <span id="id" style="color:#999;"><em>No Result Found !....</em></span>&nbsp;&nbsp;
        <img src="<?php echo W_ROOT;?>/images/add_icon.jpg" border="0" /> 
        <a style="color:#00F; text-decoration:underline; cursor:pointer;width:547px;" id="clicktoadd" onclick="$('#formaddnew').show();"><em>Add New Product</em></a>
        <br /><br /><br />  
            <?php
		}
}
function displayexit()
{
	$id = isset($_GET['id'])?$_GET['id']:'';	
	$exist = 1;
	include(S_ROOT.'/admin/product/formaddexist.php');
	exit;
}


function display()
{
	$id = $_GET['id'];	
	$sql = "SELECT * FROM tblcategory WHERE parent_id = $id";
	$result = mysql_query($sql);
?><br />
    <?php
	while($row = dbFetchassoc($result))
	{
	?>
    <option value="<?php echo $row['id'];?>"><?php echo $row['category_name'];?></option>
    <?php	
	}
}

function updatePrice(){
	$pro_id = $_POST['hidepid'];
	foreach($pro_id as $value){
		$price = $_POST['price'.$value];
		$sql_price = "UPDATE tblproduct_in_pharmacy SET price = '$price' WHERE pid = $value";
		mysql_query($sql_price);
	}
	header('Location: ' . W_ROOT.'/seller/editProductPrice.php?updatesuccess=1');
}

function publishSelected(){
	if(isset($_POST['id'])){
		if(isset($_GET['publish']) && (int)$_GET['publish']>=0 && (int)$_GET['publish']<=1){
			$publish = (int)$_GET['publish'];
		}
		else{
			header('Location: index.php');
			exit();
		}
		
		
		if(isset($_GET['pharm_id']) && (int)$_GET['pharm_id']>=0){
			$phar_id = (int)$_GET['pharm_id'];
		}
		
		//Statement to get selected id
		$id = (is_array($_POST['id']))?implode(',',$_POST['id']):$_POST['id'];
		
		//Statement to publish/unpublish selected id
		publishPro('tblproduct_in_pharmacy',$publish,$id,$phar_id);
	}
	
	header('Location: index.php?'.getAllGetParams(array('view','action','publish')));
	exit();
}

//function deletetCount(){
//	$pid = $_GET['pid'];
//	$sql = "DELETE FROM tblproduct_in_pharmacy WHERE pid = $pid";
//	mysql_query($sql);
//	exit();
//}

function deleteSelected()
{
	if(isset($_POST['id'])){
	  //Statement to get selected id
	  $id = (is_array($_POST['id']))?implode(',',$_POST['id']):$_POST['id'];
	  $selec_delet="SELECT *FROM tblproduct AS pro INNER JOIN tblimage AS im ON pro.id=im.product_id WHERE product_id IN($id)";
	   $run_query=mysql_query($selec_delet);
	  //Statment to delete selected id
	  $sql = "DELETE FROM tblproduct WHERE id IN ($id)";
	   mysql_query($sql);       
       //delete from db image       
	   if(mysql_num_rows($run_query)>0){
		     while($rows=mysql_fetch_array($run_query)){
				    $product_image=$rows['images'];
					$product_thumbnail=$rows['thumbnail'];
					$product_original_img=$rows['original_img'];
					unlink("uploads/{$product_image}");
					unlink("uploads/{$product_thumbnail}");
					unlink("uploads/{$product_original_img}");
				 }
		   }
     $del_img = mysql_query("DELETE FROM tblimage WHERE tblimage.`product_id` IN ($id)");      
	 }
	header('Location: ' . $_SESSION['shop_return_url']);	

}

function uploadPhoto($input, $uploadDir)
{
	//$image     = $_FILES[$inputName];
	$image = $input;
	$imagePath = '';
	$thumbnailPath = '';
	
	// if a file is given
	if (trim($image['tmp_name']) != '') {
		$ext = substr(strrchr($image['name'], "."), 1); //$extensions[$image['type']];

		// generate a random new file name to avoid name conflict
		//$imagePath = $image['name'];
		$imagePath = md5(rand() * time()) . ".$ext";
		
		list($width, $height, $type, $attr) = getimagesize($image['tmp_name']); 
		if ( true && $width > 500) {
			$result    = createThumbnail($image['tmp_name'], $uploadDir . $imagePath, 500);
			$imagePath = $result;
		} else {
			$result = move_uploaded_file($image['tmp_name'], $uploadDir . $imagePath);
		}	
	
		if ($result) {
			// create thumbnail
			$thumbnailPath 	=  md5(rand() * time()) . ".$ext";
			$size        	= getimagesize($uploadDir . $imagePath);
			if($size[0]>100)
				$result 		= createThumbnail($uploadDir . $imagePath, $uploadDir . $thumbnailPath, 100);
			else{
				copy($uploadDir . $imagePath, $uploadDir . $thumbnailPath);
				$result			= basename($uploadDir . $thumbnailPath);
			}
				
			// create thumbnail failed, delete the image
			if (!$result) {
				unlink($uploadDir . $imagePath);
				$imagePath = $thumbnailPath = '';
			} else {
				$thumbnailPath = $result;
			}	
		} else {
			// the product cannot be upload / resized
			$imagePath = $thumbnailPath = '';
		}
		
	}
	return array('image' => $imagePath, 'thumbnail' => $thumbnailPath);	
}
function createThumbnail($srcFile, $destFile, $width, $quality = 75)
{
	$thumbnail = '';
	
	if (file_exists($srcFile)  && isset($destFile))
	{
		$size        = getimagesize($srcFile);
		$w           = number_format($width, 0, ',', '');
		$h           = number_format(($size[1] / $size[0]) * $width, 0, ',', '');
		
		$thumbnail =  copyImage($srcFile, $destFile, $w, $h, $quality);
	}
	
	// return the thumbnail file name on sucess or blank on fail
	return basename($thumbnail);
}
function copyImage($srcFile, $destFile, $w, $h, $quality = 75)
{
    $tmpSrc     = pathinfo(strtolower($srcFile));
    $tmpDest    = pathinfo(strtolower($destFile));
    $size       = getimagesize($srcFile);

    if ($tmpDest['extension'] == "gif" || $tmpDest['extension'] == "jpg")
    {
       $destFile  = substr_replace($destFile, 'jpg', -3);
       $dest      = imagecreatetruecolor($w, $h);
       imageantialias($dest, TRUE);
    } elseif ($tmpDest['extension'] == "png") {
       $dest = imagecreatetruecolor($w, $h);
       imageantialias($dest, TRUE);
    } else {
      return false;
    }

    switch($size[2])
    {
       case 1:       //GIF
           $src = imagecreatefromgif($srcFile);
           break;
       case 2:       //JPEG
           $src = imagecreatefromjpeg($srcFile);
           break;
       case 3:       //PNG
           $src = imagecreatefrompng($srcFile);
           break;
       default:
           return false;
           break;
    }

    imagecopyresampled($dest, $src, 0, 0, 0, 0, $w, $h, $size[0], $size[1]);

    switch($size[2])
    {
       case 1:
       case 2:
           imagejpeg($dest,$destFile, $quality);
           break;
       case 3:
           imagepng($dest,$destFile);
    }
    return $destFile;

}
// end function upload


// inlink image and detlete
function UnlinkImageDelete() 
    {
	  //Statement to get selected id
	  $id = (is_array($_POST['id']))?implode(',',$_POST['id']):$_POST['id'];
	  $selec_delet="SELECT *FROM tblproduct AS pro INNER JOIN tblimage AS im ON pro.id=im.product_id WHERE product_id IN($id)";
	   $run_query=mysql_query($selec_delet);
	  //Statment to delete selected id   
        
       //delete from db image       
	   if(mysql_num_rows($run_query)>0){
		     while($rows=mysql_fetch_array($run_query)){
				    $product_image=$rows['images'];
					$product_thumbnail=$rows['thumbnail'];
					$product_original_img=$rows['original_img'];
					unlink("uploads/{$product_image}");
					unlink("uploads/{$product_thumbnail}");
					unlink("uploads/{$product_original_img}");
				 }
		   }
     $del_img = mysql_query("DELETE FROM tblimage WHERE tblimage.`product_id` IN ($id)"); 
    }
// and inlink image and detlete


// inlink image and detlete
function UnlinkSingleImageDelete() 
    {
	  //Statement to get selected id
	  $id = (is_array($_POST['DelImage']))?implode(',',$_POST['DelImage']):$_POST['DelImage'];
	  $selec_delet="SELECT * FROM tblimage WHERE tblimage.`id` IN ($id)";
	   $run_query=mysql_query($selec_delet);
	  //Statment to delete selected id   
        
       //delete from db image       
	   if(mysql_num_rows($run_query)>0){
		     while($rows=mysql_fetch_array($run_query)){
				    $product_image=$rows['images'];
					$product_thumbnail=$rows['thumbnail'];
					$product_original_img=$rows['original_img'];
					unlink("uploads/{$product_image}");
					unlink("uploads/{$product_thumbnail}");
					unlink("uploads/{$product_original_img}");
				 }
		   }
     $del_img = mysql_query("DELETE FROM tblimage WHERE tblimage.`id` IN ($id)"); 
    }
// and inlink image and detlete


